package com.hyjoy.service.impl;

import com.hyjoy.dao.OrderDao;
import com.hyjoy.dao.impl.OrderDaoImpl;
import com.hyjoy.entity.Order;
import com.hyjoy.entity.OrderItem;
import com.hyjoy.entity.PageBean;
import com.hyjoy.service.OrderService;
import com.hyjoy.util.BeanFactory;
import com.hyjoy.util.DataSourceUtils;

import java.util.List;

public class OrderServiceImpl implements OrderService {

    @Override
    /**
     * 保存订单
     */
    public void save(Order order) throws Exception {
        try {
            //获取dao
            OrderDao od = new OrderDaoImpl();
            //1.开启事务
            DataSourceUtils.startTransaction();

            //2.向orders表中插入一条
            od.save(order);

            //3.向orderitem中插入n条
            for (OrderItem oi : order.getItems()) {
                od.saveItem(oi);
            }

            //4.事务控制
            DataSourceUtils.commitAndClose();
        } catch (Exception e) {
            e.printStackTrace();
            DataSourceUtils.rollbackAndClose();
            throw e;
        }
    }

    @Override
    public PageBean<Order> findMyOrdersByPage(int pageNumber, int pageSize, String uid) throws Exception {
        OrderDao orderDao = new OrderDaoImpl();
        PageBean<Order> pageBean = new PageBean<>(pageNumber, pageSize);
        int totalRecord = orderDao.getTotalRecord(uid);
        pageBean.setTotalRecord(totalRecord);
        // 查询当前页数据，设置当前页数据
        List<Order> data = orderDao.findMyOrdersByPage(pageBean, uid);
        pageBean.setData(data);
        return pageBean;
    }

    @Override
    public Order getById(String oid) throws Exception {
        OrderDao orderDao = new OrderDaoImpl();
        return orderDao.getById(oid);
    }

    @Override
    public void update(Order order) throws Exception {
        OrderDao orderDao = new OrderDaoImpl();
        orderDao.update(order);
    }

    @Override
    public List<Order> findAllByState(String state) throws Exception {
        OrderDao orderDao = new OrderDaoImpl();
        return orderDao.findAllByState(state);
    }

}
